import os
import socket
import time
import requests
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileSystemEvent
import ssl



class PrintOnFileCreateHandler(FileSystemEventHandler):
    def __init__(self, cups_server,printer_name,watch_folder, file_extension='.pdf'):
        self.cups_server = cups_server
        self.printer_name =printer_name
        self.watch_folder = watch_folder
        self.file_extension = file_extension

    def on_created(self, event):
        if not event.is_directory and event.src_path.endswith(self.file_extension):
            print(f"find file:{event.src_path}")
            self.print_file(event.src_path)
            os.remove(event.src_path)  #完成后删除

    def print_file(self, file_path):
        with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
            try:
                s.connect((self.cups_server, 8000))
                print("connect success")
            except Exception:
                print("connect failed")
            self.create_ipp_request(file_path)
            request = self.create_ipp_request(file_path)
            s.sendall(request)

    def create_ipp_request(self, file_path):
        request = b'POST/printers/%s HTTP/1.1\r\n'%self.printer_name.encode('utf-8')
        request += b'Content-Type: application/ipp\r\n'
        request += b'Host: 192.168.50.70\r\n'
        request += b'User-Agent: CUPS/2.4.8\r\n'
        request += b'Connection: Keep-Alive\r\n'
        with open(file_path, 'rb') as f:
            data = f.read()

        content_length = len(request)+len(data)

        request += b'Content-Length: %d\r\n'%content_length

        request += b'\r\n'
        request += data

        return request


event_handler = PrintOnFileCreateHandler(cups_server='192.168.50.70',printer_name='test',watch_folder=r'D:\test')
observer = Observer()
observer.schedule(event_handler, event_handler.watch_folder, recursive=False)

observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()
